package com.nexgo.payment.action.online.upload;

import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.databases.TransRecord;
import com.nexgo.payment.entity.MessageData;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.payment.util.TransUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by xiaox on 2017/8/16.
 */

/**
 * 冲正
 */
class Reversal extends Upload {
    private final Logger log;
    private OnUploadListener mListener;
    private TransRecord mTransRecord;
    private boolean mForceBreak;
    private final List<TransRecord> mTransRecords;
    private int mIdx = 0;

    Reversal(DataSource repository) {
        super(repository);
        log = LoggerFactory.getLogger(getClass().getSimpleName());
        //正常情况只会存在一笔冲正数据
        mTransRecords = mRepository.getReversalTransRecords();
    }

    @Override
    TransData buildTransData() {
        log.debug("冲正流水号 {}", mTransRecord.getTraceNum());
        TransData transData = new TransData();
        transData.setTransType(TransType.REVERSAL);
        transData.setOrgTraceNum(mTransRecord.getTraceNum());
        return transData;
    }

    @Override
    public void sendTrans(OnUploadListener listener) {
        mListener = listener;
        sendOrComplete();
    }

    @Override
    void onTransResponseCheckError(String responseCode) {
        //判断是否返回A0，是则强制退出，需要重新签到
        if (TransUtils.isNeedReLogin(responseCode)) {
            updateTransRecordReversalCode("A0");
            mRepository.setParamValue(PreferencesConstants.IS_NEED_LOGIN, "1");
            mRepository.syncParamValue();
            //退出
            mForceBreak = true;
            return;
        } else {
            updateTransRecordReversalCode("06");
        }
    }

    @Override
    void onTransResponse(MessageData messageData) {
        log.debug("冲正成功");
        eraseTransRecordReversal();
    }

    @Override
    void onTransTimeout() {
        updateTransRecordReversalCode("98");
        //超过最大上送次数当成功处理
        if (isOverMaxReUploadTimes()) {
            log.debug("超过最大次数");
            eraseTransRecordReversal();
        }
        sendOrComplete();
    }

    @Override
    void onTransFailed() {
        mListener.onUploadFailed();
    }

    @Override
    void onTransComplete() {
        if (mForceBreak) {
            onTransFailed();
        } else {
            //超过最大上送次数当成功处理
            if (isOverMaxReUploadTimes()) {
                log.debug("超过最大次数");
                eraseTransRecordReversal();
            }
            sendOrComplete();
        }
    }

    private void sendOrComplete() {
        if (hasNext()) {
            log.debug("存在需要上送的冲正");
            mListener.onShowTip(App.sContext.getString(R.string.reversal_upload));
            send();
        } else {
            log.debug("冲正结束");
            mListener.onUploadComplete();
        }
    }

    @Override
    public boolean isOverMaxReUploadTimes() {
        return sUploadCounter >= getMaxReUploadTimes();
    }

    private int getMaxReUploadTimes() {
        return Integer.parseInt(StringUtils.firstNonEmpty(mRepository.getParamValue(PreferencesConstants.REVERSAL_UPLOAD_TIMES), "3"));
    }

    private boolean hasNext() {
        if (mTransRecords == null) {
            return false;
        }
        for (int i = mIdx; i < mTransRecords.size(); i++) {
            mIdx = i + 1;
            mTransRecord = mTransRecords.get(i);
            return true;
        }
        return false;
    }

    private void eraseTransRecordReversal() {
        log.debug("清除冲正标志");
        mTransRecord.setIsNeedReversal(false);
        mRepository.updateTransRecord(mTransRecord);
    }

    private void updateTransRecordReversalCode(String code) {
        log.debug("重置冲正原因码 {}", code);
        mTransRecord.setReversalCode(code);
        mRepository.updateTransRecord(mTransRecord);
    }

    @Override
    boolean check(MessageData messageData) {
        return super.check(messageData);
    }
}
